       var lastSelectedRow;
       var orderId=0;
      $(function(){

            function initOrderItemsSubGird(subgrid_id, row_id){

                    var subgrid_table_id, pager_id;
                    subgrid_table_id = subgrid_id+"_t";

                    $("#"+subgrid_id).html("<table id='"+subgrid_table_id+"' class='scroll'></table><div id='"+pager_id+"' class='scroll'></div>");

                        jQuery("#"+subgrid_table_id).jqGrid({
                                        url:"listOrderItem",
                                        datatype: "json",
                                        postData: {orderId: row_id},
                                        colNames : ['Item','Qty','Unit','Line Total'],
                                        colModel: [
                                                {name:"productName",index:"product.name",width:80,key:true},
                                                {name:"quantity",index:"quantity",width:70,align:"right"},
                                                {name:"unitPrice",index:"unitPrice",width:70,align:"right",formatter:'currency' ,formatoptions:currencyformatoptions},
                                                {name:"total",index:"total",width:70,align:"right",sortable:false,formatter:'currency' ,formatoptions:currencyformatoptions}
                                                ],
                                        rowNum:20,
                                        sortname: 'num',
                                        sortorder: "asc",
                                        height: '100%',
                                        autowidth : true,
                                        jsonReader : {root:"orderItems"},
                                    });
            }

            function initOrderGrid(){
                        jQuery("#orderGrid").jqGrid({
                             url:'search',
                             datatype: "json",
                             height: 400,
                             autowidth : true,
                             colNames:['Order No','Date', 'Customer', 'Amount','Total','Status','Notes','Action'],
                             colModel:[
                                    {name:'orderId',index:'orderId', width:55,key:true},
                                    {name:'orderDate',index:'orderDate', width:90},
                                    {name:'customerName',index:'customerName', width:100},
                                    {name:'totalOrderAmount',index:'totalOrderAmount', width:80, align:"right"},
                                    {name:'totalOrderAmount',index:'totalOrderAmount', width:80,align:"left",formatter:'currency' ,formatoptions:currencyformatoptions},
                                    {name:'status',index:'status', width:80,align:"center"},
                                    {name:'comments',index:'comments', width:150, sortable:false},
                                    { name : 'orderId', index:'orderId', sortable:false,editable:false ,formatter:actionFormat, unformat:actionUnFormat},
                                    ],
                              postData: {
                                id: function() { return $("#search-orderId").val(); },
                                status: function() { return $("#search-status").val(); },
                                fromDate: function() { return $("#fromDate").val(); },
                                toDate: function() { return $("#toDate").val(); }
                              },
                              rowNum:20,
                              rowList:[10,20,30],
                              pager: '#orderGridPager',
                              sortname: 'orderDate',
                              viewrecords: true,
                              footerrow : true,
                              userDataOnFooter : true,
                              altRows : true,
                              sortorder: "desc",
                              sortname: "orderId",
                              multiselect: false,
                              subGrid : true,
                              subGridUrl: 'listOrderItem',
                              subGridOptions: {
                                     "plusicon"  : "ui-icon-triangle-1-e",
                                     "minusicon" : "ui-icon-triangle-1-s",
                                     "openicon"  : "ui-icon-arrowreturn-1-e",
                                    "reloadOnExpand" : false,
                                    "selectOnExpand" : true
                                },
                                subGridRowExpanded: initOrderItemsSubGird
                               ,
                              caption: "Orders" ,
                              jsonReader : {root:"orders"},
                                    gridComplete: function(){

                                          }
                                     }
                             );
                }
            initOrderGrid();

           function actionFormat( cellvalue, options, rowObject ){
                return "<button class='btn btn-xs btn-default btn-quick' title='Order Detail' onclick=\"showOrderDetail('"+cellvalue+"');\"><i class='fa fa-pencil'></i></button>";
             }
               function actionUnFormat( cellvalue, options, cell){
                      	return $('img', cell).attr('src');
                  }

            jQuery("#orderGrid").jqGrid('navGrid','#orderGridPagere',{edit:false,add:false,del:false});

                 jQuery("a.get_selected_ids").bind("click", function() {
                		s = jQuery("#productGrid").jqGrid('getGridParam', 'selarrrow');

                	});
              initGridUI();



            $( "#save-order-button").click(function () {

             		var options = {
                            url:       'save' ,
                            type:      'post' ,
                            dataType:  'json' ,
                            clearForm: true  ,
                            resetForm: true  ,
                            timeout:   9000  ,
                            success:    function() {
                               grid.trigger("reloadGrid");
                                $('#orderForm').modal('hide')
                             }  ,
                              error:    function() {
                               alert('Error');
                             }
                        };

					      var customerOrderInfo = $("#order-customer-info-form").serializeArray();
                          var customerSummaryInfo  = $("#order-summary-info-form" ).serializeArray();
                          var customerShippingInfo = $( "#order-shipping-info-form" ).serializeArray();
                          var newArray1 = $.merge(customerOrderInfo, customerSummaryInfo);
                          var newArray2 = $.merge(customerOrderInfo, customerShippingInfo);
                           $.ajax({
                                         url: "save",
                                         dataType: "json",
                                         method:"post",
                                         data: customerOrderInfo,
                                        success: function( data ) {
                                           response($.map(data.products, function(item) {
                                                        return {
                                                  label: item.name,
                                                  value: item.productId,
                                                  product:item,
                                      }
                                         }));

                                  }
                                  });

			});
			 $( "#search-item").button().click(function () {

             	jQuery('#orderItemGrid').trigger("reloadGrid");
			});

			 $( "#search-order").button().click(function () {

                         	jQuery('#orderGrid').trigger("reloadGrid");
            			});


			$('#orderForm').modal({
                    keyboard: false ,
                    backdrop: false,
                    show: false
            })

                 var mySaveOptions = {
                                 successfunc: function(response) {

                                    var responseJs=    jQuery.parseJSON( response.responseText );

                                      return true;
                                 },
                                url:'saveItem',
                                extraparam: {

                                    params1:function(){
                                         return 1;
                                    },
                                    params2:function(){
                                    return 2;
                                   },
                                   orderId:function(){
                                         return orderId;
                                   }
                                },
                                aftersavefunc: function (rowId, response) {


                                   var responseJs=    jQuery.parseJSON( response.responseText );


                                    $(this).jqGrid('setRowData', rowId, { 'itemId': responseJs.itemId, 'orderId': responseJs.orderId ,'total': responseJs.total });

                                     orderId=responseJs.orderId;

                                     $("#orderId").val(orderId);

                                    displayOrderSummary();

                                },
                                 errorfunc: function (rowid, response, options) {
                                     alert(response.responseText);
                                  },
                                  restoreAfterError:false
                            };



                var  myEditParam = {
                                        keys: true,
                                        oneditfunc: function (id) {
                                            lastSelectedRow = id;
                                        },
                                        afterrestorefunc: function (id) {
                                            lastSelectedRow = undefined;
                                        },
                                        aftersavefunc: function (id) {

                                            var $this = $(this),
                                                rate = $this.jqGrid("getCell", id, "rate"),
                                                qty = $this.jqGrid("getCell", id, "qty"),
                                                newAmount = parseFloat(rate) * parseFloat(qty);
                                            $this.jqGrid("setCell", id, "amount", newAmount);
                                            editingRowId = undefined;
                                             displayOrderSummary();
                                        }
                                    };

                  var itemDeleteOptions = {
                                    keys: true,
                                    editbutton : false,
                                    delbutton : true,
                                    onEdit: function (id) {
                                                              alert(id);
                                                                    if (typeof (lastSel) !== "undefined" && id !== lastSel) {
                                                                      //  cancelEditing(grid);
                                                                    }
                                                                    lastSel = id;
                                                                },
                                     delOptions: {
                                      mtype: 'POST',
                                      url: 'removeItem',
                                      processing:true,
                                      delData: {
                                                itemId: function () {
                                                  var itemId = $("#" + lastSelectedRow + "_itemId").val();
                                                  return itemId;
                                                }
                                          },

                                    },
                                     editOptions : {
                                                   size:10, maxlength: 15,mtype: 'POST',
                                                   required:true,
                                                   url: 'saveItem',
                                                   editData: {
                                                   id: '45',
                                                    orderId: function () {  return 666; }
                                                  },
                                                  oneditfunc: function (id) {
                                                                    alert(id);
                                                                          editingRowId = id;
                                                                      },
                                                                      afterrestorefunc: function (id) {
                                                                          editingRowId = undefined;
                                                                      },
                                                                      aftersavefunc: function (id) {
                                                                          var $this = $(this),
                                                                              rate = $this.jqGrid("getCell", id, "unitPrice"),
                                                                              qty = $this.jqGrid("getCell", id, "discount"),
                                                                              newAmount = parseFloat(rate) * parseFloat(qty);
                                                                          $this.jqGrid("setCell", id, "total", newAmount);
                                                                          editingRowId = undefined;
                                                                      }

                                              }

                                };
                                   function recomputeAmount() {

                                                   var rate = $("#" + lastSelectedRow + "_unitPrice").val(),
                                                   qty = $("#" + lastSelectedRow + "_quantity").val(),
                                                      discount = $("#" + lastSelectedRow + "_discount").val();

                                                    var newAmount = parseFloat(rate) * parseFloat(qty) -discount;
                                                    $("#" + lastSelectedRow + "_total").val(isFinite(newAmount) ? newAmount : 0);


                                                }

            var numInput = {
                        type: 'keydown',
                        fn: function (e) {
                            var key = e.which;
                            // '0' <= key <= '9' or key = '.'


                            if ((key < 48 || key > 57) && key !== $.ui.keyCode.PERIOD &&
                                key !== $.ui.keyCode.TAB && key !== $.ui.keyCode.ESCAPE && key !== $.ui.keyCode.ENTER) {
                                return false;
                            }
                             recomputeAmount();
                            if(key === $.ui.keyCode.ENTER ){
                             jQuery('#orderItemGrid').jqGrid('saveRow',lastSelectedRow,mySaveOptions);
                            }
                        }
                    };
                    var recompute = {
                                        type: 'focusout',
                                        fn: function (e) {
                                            recomputeAmount();
                                        }
                                    };


  function editGridRow(rowId){

     if($($("#orderItemGrid").jqGrid("getInd",rowId,true)).attr("editable") === "1") {
     return false;
    }
     jQuery('#orderItemGrid').jqGrid('editRow',rowId,myEditParam);
    lastSelectedRow=rowId;
    return true;

  }
     jQuery(".orderItemGrid").jqGrid({
             emptyrecords: "No items added  to order",
             loadtext: "Loading...",
             pgtext : "Page {0} of {1}",
             prmNames:{page:"page",rows:"rows", sort:"sidx", order:"sord", search:"_search", nd:"nd", id:"id", oper:"oper", editoper:"edit", addoper:"add", deloper:"del", subgridid:"id", npage:null, totalrows:"totalrows"} ,
             editurl: 'saveItem',
             datatype:"local",
            loadonce: true,
             autowidth:true,
             jsonReader : {root:"orderItems"},
             colNames:['Action','SKU','Item Name','Unit Price', 'Quantity', 'Discount','Total','#Item','#Order','#Item'],
             autowidth : true,
             colModel:[
                {name: 'action', width:80, fixed:true, sortable:false, resize:false, formatter:'actions', formatoptions:itemDeleteOptions},
                {name:'productSku',index:'productSku', width:75,sortable:false},
                {name:'productName',index:'productName', width:375},
                {name:'unitPrice',index:'unitPrice', width:90, editable:true,formatter:'currency',editrules:{number:true,maxlength:5},
                                                                                                     editoptions: {
                                                                                                         dataInit: function (elem) { $(elem).focus(function () { this.select(); }) },
                                                                                                         dataEvents: [ numInput, recompute ]
                                                                                                     }
                                                                                                 },
                {name:'quantity',index:'quantity', width:95,editable:true,formatter:'number',editrules:{number:true,maxlength:5},
                                                                                                         editoptions: {
                                                                                                                    dataInit: function (elem) { $(elem).focus(function () { this.select(); }) },
                                                                                                                    dataEvents: [ numInput, recompute ]
                                                                                                                      }
                                                                                                },
                {name:'discount',index:'discount', width:75, align:"center",editable:true,formatter:'currency',editrules:{number:true,maxlength:5},
                                                                                       editoptions: {
                                                                                          dataInit: function (elem) { $(elem).focus(function () { this.select(); }) },
                                                                                          dataEvents: [ numInput, recompute ]
                                                                              }
                                                                                                                                                               },

                {name:'total',index:'total', width:105,align:"center",editable:true, editoptions: {disabled: true},formatter:'currency'},
                {name:'productId',index:'productId', width:75,sortable:false,hidden:true,key:true},
                {name:'orderId',index:'orderId', width:75,sortable:false,hidden:true,editable:true, editoptions: {edithidden: true}},
                {name:'itemId',index:'id', width:75,sortable:false,hidden:true,editable:true, editoptions: {edithidden: true}}],
                sortname: 'itemId',
                viewrecords: true,
                sortorder: "id",
                caption:"Order items ",
                onSelectRow: function(id,status){
                    if(typeof (lastSelectedRow) !== "undefined" && id !== lastSelectedRow ){
                      jQuery('#orderItemGrid').jqGrid('saveRow',lastSelectedRow,mySaveOptions);
                        return editGridRow(id);

                    }else{
                         editGridRow(id);
                         return true;
                    }
                 },
                 ondblClickRow: function (rowid) {

                    }
             ,afterInsertRow : function (rowid,
                                           rowdata,
                                           rowelem){
                                      //    jQuery('#jDeleteButton_'+rowid).addClass('ui-state-disable');
              } ,
              beforeSelectRow : function(rowid,event){
                return true;
              }
              }
               );

               initProductSearch(selectProduct);

               initAccountSearch(selectAccount);

                 jQuery("#orderItemGrid").focusout(function (e) {
                     if (e.relatedTarget) {
                         var $related =  $("#orderItemGrid").find(e.relatedTarget);
                         if ($related.length <= 0 && lastSelectedRow) {

                              jQuery('#orderItemGrid').jqGrid('saveRow',lastSelectedRow,mySaveOptions);
                         }
                     }
                 });



                  jQuery("#orderItemGrid").focusout(function (e) {

                     if (e.relatedTarget) {
                         var $related = grid.find(e.relatedTarget);
                         if ($related.length <= 0 && lastSelectedRow) {
                             grid.jqGrid('saveRow', lastSelectedRow);
                         }
                     }
                 });

        $("#fromDateDiv").on("dp.change", function (e) {
            $('#toDateDiv').data("DateTimePicker").minDate(e.date);
        });
        $("#toDateDiv").on("dp.change", function (e) {
            $('#fromDateDiv').data("DateTimePicker").maxDate(e.date);
        });



            $('input.payment').focusin(function()
                {

                   $(this).select();

                });


             $('input.currency').change(function()
                 {
                    displayOrderSummary();

                 });

               $('input.payment').change(function()
                   {
                    var total=0;

                     if($('#payment1000').val())
                      {
                      total=total+$('#payment1000').val() *1000;
                       $('#paymentH1000').val($('#payment1000').val() *1000);
                       $('#paymentH1000').formatCurrency('#paymentTotal1000');
                      }
                     if($('#payment500').val())
                       {
                        total=total+$('#payment500').val() *500;
                        $('#paymentH500').val($('#payment500').val() *500);
                        $('#paymentH500').formatCurrency('#paymentTotal500');
                     }
                     if($('#payment100').val())
                     {
                      total=total+$('#payment100').val() *100;
                        $('#paymentH100').val($('#payment100').val() *100);
                        $('#paymentH100').formatCurrency('#paymentTotal100');
                     }

                    if($('#payment50').val())
                     {
                      total=total+$('#payment50').val() *50;
                        $('#paymentH50').val($('#payment50').val() *50);
                        $('#paymentH50').formatCurrency('#paymentTotal50');
                     }
                      if($('#payment10').val())
                        {
                         total=total+$('#payment10').val() *10;
                         $('#paymentH10').val($('#payment10').val() *10);
                         $('#paymentH10').formatCurrency('#paymentTotal10');
                        }
                     $('#paymentTotal').val(total);
                     $('#paymentTotal').formatCurrency();
                  });




            function displayOrderSummary(){

              var orderSubTotalAmount =  jQuery("#orderItemGrid").jqGrid('getCol', 'total', false, 'sum');
              $('#orderSubTotalAmount').val(orderSubTotalAmount);
               var orderShippingAmount=$('#orderShippingAmount').val();
               var orderDiscount=$('#orderDiscount').val();
               var orderPayment=$('#orderPayment').val();
               var newAmount = parseFloat(orderSubTotalAmount) +parseFloat(orderShippingAmount) -parseFloat(orderDiscount);
                $('#totalOrderAmount').val(newAmount);
                $('#orderDueAmount').val(newAmount-parseFloat(orderPayment));
            }

              jQuery(".order-customer-info-edit").bind("click", function() {
                  var formObj=   $(this).closest("form");
                       customerSearchInfoBlock(true,formObj);
            	});

             jQuery("#applyPayment").bind("click", function() {
                    $('#orderPayment').val( jQuery("#paymentTotal").val());
                    displayOrderSummary();
              	});


            jQuery(".order-btn").bind("click", function() {

               console.log($(this).data("block"));

                var options= {'keyboard':false,'show':true};

                $($(this).data("block")).modal(options);

          	});

    });


function selectAccount( event, ui ) {
                  var customerInfo = ui.item.customer;

                       var formObj=   $(this).closest("form");

                     if(customerInfo){
                               formObj.find( "#customerId" ).val(customerInfo.customerId);
                               formObj.find( "#customer-company" ).html(customerInfo.company);
                                formObj.find( "#customer-name" ).html(customerInfo.name);
                               formObj.find( "#customer-address" ).html(customerInfo.address.city);
                               formObj.find( "#customer-mobile" ).html(customerInfo.mobile);
                              customerSearchInfoBlock(false,formObj);
                          }
                   $(this).val("");
                    return false;
           }

         function selectProduct(event,ui){
                var orderItemExist = $("#orderItemGrid:visible").getRowData(ui.item.product.productId);
                                          var id=ui.item.product.productId;


                                           if(typeof orderItemExist === "undefined" || typeof orderItemExist.productId === "undefined")
                                           {

                                                 var orderItem =new Object();
                                                 orderItem.productId=ui.item.product.productId;
                                                 orderItem.orderId=orderId;
                                                 orderItem.productName=ui.item.product.name;
                                                 orderItem.productSku=ui.item.product.sku;
                                                 orderItem.unitPrice=ui.item.product.regPrice;
                                                 orderItem.quantity=1;
                                                 orderItem.discount=0;
                                                 orderItem.tax=0;
                                                 jQuery("#orderItemGrid:visible").jqGrid('addRowData',ui.item.product.productId, orderItem, 'last');
                                                 jQuery("#orderItemGrid:visible").jqGrid ('setSelection', orderItem.productId);

                                           }else{

                                              if(id == lastSelectedRow){

                                                var quantity=parseFloat($("#"+lastSelectedRow+"_quantity","#orderItemGrid:visible").val() )+1;
                                                var unitPrice=parseFloat($("#"+lastSelectedRow+"_unitPrice","#orderItemGrid:visible").val());
                                                var discount=parseFloat($("#"+lastSelectedRow+"_discount","#orderItemGrid:visible").val());

                                                $("#"+id+"_quantity","#orderItemGrid:visible").val(quantity);
                                                $("#"+id+"_total","#orderItemGrid:visible").val(quantity*unitPrice-discount);

                                              }else
                                              {
                                                 orderItemExist.quantity=parseFloat(orderItemExist.quantity)+1;
                                                 orderItemExist.total=orderItemExist.quantity*orderItemExist.unitPrice -orderItemExist.discount;
                                                 var result=jQuery("#orderItemGrid:visible").jqGrid('setRowData',orderItemExist.productId, orderItemExist);
                                                 jQuery("#orderItemGrid:visible").jqGrid ('setSelection', orderItemExist.productId);
                                              }


                                          }
                  $(this).val("");
                    return false;
         }
         function customerSearchInfoBlock(enableSearch,formObj){
                 if(enableSearch){
                    formObj.find( "#customerinfo" ).removeClass("col-sm-1 hide");
                    formObj.find( "#customerinfo" ).addClass("col-sm-7");
                    formObj.find( "#order-customer-info" ).removeClass("col-sm-7");
                    formObj.find( "#order-customer-info" ).addClass("col-sm-3 hide");
                    formObj.find( "#customerDetail" ).addClass("hide");
                    formObj.find( "#customerId" ).val('');
                 }else

                 {
                    formObj.find( "#customerinfo" ).removeClass("col-sm-5");
                    formObj.find( "#customerinfo" ).addClass("col-sm-1 hide");
                    formObj.find( "#order-customer-info" ).removeClass("col-sm-3");
                    formObj.find( "#order-customer-info" ).addClass("col-sm-7");
                    formObj.find( "#order-customer-info" ).removeClass("hide");
                 }
         }

	            function showOrderBlock(orderType){
                    	  var modelObj;

                    	  var options= {'keyboard':false,'show':true};
                            if(orderType == 'PO'){


                               modelObj= $('#purchaseOrderBlock');
                            }
                             if(orderType == 'BL'){
                                modelObj= $('#billBlock');
                             }
                            if(orderType == 'SO'){
                               modelObj= $('#saleOrderBlock');
                            }
                            if(orderType == 'IN'){
                               modelObj= $('#invoiceBlock');

                            }
                            if(orderType == 'IR'){
                                 modelObj= $('#itemReceiptBlock');

                             }
                             if(orderType == 'SR'){
                                  modelObj= $('#salesReceiptBlock');

                             }
                             modelObj.modal(options);

                             return modelObj;

      	           }

            function showOrderDetail(index){

                         $.ajax({url: "getOrderDetails", dataType: "json",data: {
                                                   "id": index
                                         },success: function(orderObj){


                                           if(orderObj.orderId)
                                           {
                                                   var newUrl='listOrderItem?orderId='+orderObj.orderId;
                                                 var modelObj=  showOrderBlock(orderObj.orderType);
                                                 loadFormData(orderObj,'',modelObj);

                                                 modelObj.find('#orderItemGrid').setGridParam({url:newUrl,datatype:'json',loadonce:false});
                                                  modelObj.find('#orderItemGrid').trigger("reloadGrid");
                                                  // showCustomerInfo(productObj.customer);

                                                 
                                           }
                                            else{

                                            }

                         }});

                  }